package com.spring.demo.core.dao.jdbc;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.PreparedStatementCreator;
import org.springframework.jdbc.support.GeneratedKeyHolder;
import org.springframework.jdbc.support.KeyHolder;

import com.spring.demo.core.dao.IMemberDao;
import com.spring.demo.core.entity.Member;

public class MemberDao implements IMemberDao {

	private JdbcTemplate jdbcTemplate;
	private static final String INSERT_MEMBER_SQL = "insert into member(name, zip, street) values(?, ?, ?)";
	private static final String SELECT_MEMBER_SQL = "select id, name, zip, street from member where id=?";

	@Autowired
	public void setDataSource(
			@Qualifier("embeddedDataSource") DataSource dataSource) {
		jdbcTemplate = new JdbcTemplate(dataSource);
	}

	@Override
	public void saveMember(final Member member) {
		KeyHolder holder = new GeneratedKeyHolder();
		PreparedStatementCreator psc = new PreparedStatementCreator() {
			@Override
			public PreparedStatement createPreparedStatement(Connection con)
					throws SQLException {
				PreparedStatement ps = con.prepareStatement(INSERT_MEMBER_SQL);
				ps.setString(1, member.getName());
				ps.setString(2, member.getZip());
				ps.setString(3, member.getStreet());
				return ps;
			}
		};
		jdbcTemplate.update(psc, holder);
		member.setId(holder.getKey().longValue());
		if ("zhangsan".equals(member.getName())) {
			throw new RuntimeException("阻止事务提交");
		}
	}

	@Override
	public Member getMemberById(Long id) {
		try {
			return jdbcTemplate.queryForObject(SELECT_MEMBER_SQL,
					new Object[] { id }, new Member());
		} catch (DataAccessException e) {
		}
		return null;
	}

	@Override
	public List<Member> getAllMembers() {
		// TODO Auto-generated method stub
		return null;
	}

}
